package com.macrolab.code.api

import com.macrolab.util.MyTools
import com.macrolab.util.VelocityUtil
import org.apache.commons.io.FileUtils
import org.apache.poi.hssf.usermodel.HSSFCell
import org.apache.poi.hssf.usermodel.HSSFRow
import org.apache.poi.hssf.usermodel.HSSFSheet
import org.apache.poi.hssf.usermodel.HSSFWorkbook
import org.apache.poi.ss.usermodel.Row

/**
 * 代码生成
 * 由excel的接口定义生成controller类
 *
 * @author macroLu 2019-4-18
 *
 */
// ============= 接口定义excel =============
//def excelFile = projPath + "doc\\TSMApit接口定义.xls"
def excelFile = "D:\\my\\workspace\\tsm-backend\\doc\\TSMApit接口定义.xls"

// ============= 模板文件 ==================
def classTemplateFile = "APIController.java.vm"
def methodTemplateFile = "APIControllerMethod.java.vm"

// ============= 模板变量 ==================
def packageName = "com.macrolab.api.web.controller.tsm"

// ============= 代码生成的路径 =============
def projPath = "D:\\my\\workspace\\genCode\\"
def outputPath = projPath + "output/tsm/"

MyTools.createTmpDir(outputPath)
println "代码生成位置 ==> ${outputPath}"


// ================== 开始解析excel ======================
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(new File(excelFile)));
workbook.setMissingCellPolicy(Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
def controllers = [:] // <controllerName : methods>

def colHeader = [:]
HSSFSheet sheet = workbook.getSheet("Sheet1");
int rows = sheet.physicalNumberOfRows;

// 提取标题行
int colId = 0
HSSFRow headerRow = sheet.getRow(0);
headerRow.each { col ->
    if (MyTools.isNotEmpty(col.toString())) {
        colHeader.put(colId++, col.toString())
    }
}
println "接口定义文件：" + excelFile
println "接口定义标题行：" + colHeader;

//忽略第一行,标题行
(1..<rows).each { r ->
    HSSFRow row = sheet.getRow(r);
    def cells = row.physicalNumberOfCells;
    def controllerName = ""
    def method = [:]
    def genFlag = "", usage = "", baseUrl = "", methodUrl = "", params = ""
    (0..<cells).each { c ->
        HSSFCell cell = row.getCell(c);
        def colName = colHeader.get(c)
        switch (colName) {
            case "是否生成":
                genFlag = cell.toString()
                break
            case "Controller":
                controllerName = cell.toString()
                break
            case "api编码":
                method += [code: cell.toString()]
                break
            case "api名称":
                method += [apiName: cell.toString()]
                break
            case "调用方式":
                method += [method: cell.toString()]
                break
            case "BaseURL":
                baseUrl = cell.toString()
                break
            case "方法URL":
                methodUrl = cell.toString()
                break
            case "params":
                params = cell.toString()
                break
            case "功能内容简述":
                usage = cell.toString()
                break
        }
    }
    if (genFlag == "生成") {
        method += [apiGroup: controllerName.toUpperCase()]
        method += [usage: usage]
        method += [baseUrl: baseUrl]
        method += [methodUrl: methodUrl]
        method += [params: params]
        def methods = controllers.get(controllerName) ? controllers.get(controllerName) : []
        methods.add(method)
        controllers.put(controllerName, methods)
    }
}
//println controllers
// ================ 模板文件 ===============
def methodf = new File(methodTemplateFile)

controllers.each { controllerName, methods ->
    def methodCode = ""
    def baseUrl = ""
    methods.each { method ->
        baseUrl = method.baseUrl
        def template = new groovy.text.GStringTemplateEngine().createTemplate(methodf)
        String response = template.make(method)
        methodCode += response + "\n\n"
    }

    // 生成 java文件类名
    def className = MyTools.buildCamelName(controllerName, true) + "Controller"
    def binding = [
            packageName: packageName,
            methodCode : methodCode,
            className  : className,
            baseUrl    : baseUrl,
    ]

    def classf = new File(classTemplateFile)
    def template = new groovy.text.GStringTemplateEngine().createTemplate(classf)
    String response = template.make(binding)
    File classFile = new File(outputPath + "${className}.java")
    classFile.newWriter('GBK')
    classFile << response


    VelocityUtil.inputEncoding="UTF-8";
    VelocityUtil foo = new VelocityUtil();
//    List a = new ArrayList<String>();
//    a.add("1");
//    a.add("2");
//    foo.setId(a);
    String content= VelocityUtil.getContentByPath(methodTemplateFile, foo);

    FileUtils.writeStringToFile(new File("E://test.txt"), content);
    System.out.print(content);



    println "生成RestApi java class ==> [项目根目录]/${outputPath}${className}.java"
}


